package knowlwdge_graph.knowledge_etl.entity_etl;

import common.dao.postgre.PostGreJDBCDao;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by julianzliu on 4/25/2017.
 */
public class EntityPostgres {
    static final org.slf4j.Logger logger = LoggerFactory.getLogger(EntityPostgres.class);

    private PostGreJDBCDao postGreJDBCDao;
    private Connection conn;

    public EntityPostgres(){
        this.postGreJDBCDao = new PostGreJDBCDao();

        this.conn = this.postGreJDBCDao.getConn();

        if(this.conn == null){
            logger.error("[EntityPostgres] Connection Failed!!!\n\n");
        }
    }


    /*
   每次抽取实体之后，在数据库中保存 id
   表结构：
   CREATE TABLE yagoentities (
     ts timestamp default current_timestamp,
     id string not null,
     status integer not null
   )
    */
    public boolean storeEntityStatus(String id, Integer status){
        String sql = String.format("insert into yagoentities (id,status) values ('%s',%d);", id,status);
        logger.info("[storeEntityStatus] sql = {}", sql);
        boolean success = true;
        try {
            Statement stmt = conn.createStatement();
            success = stmt.execute(sql);
            stmt.close();
        } catch (SQLException e){
            e.printStackTrace();
            success = false;
        }
        return success;
    }

    public Integer getEntityStatus(String id){
        String sql = String.format("select * from yagoentities where id = '%s' order by ts desc limit 1;", id);
        logger.info("[yagoentities] sql = {}", sql);
        Integer status = 0;
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = null;
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                status = rs.getInt("status");
            }
            rs.close();
            stmt.close();
        } catch (SQLException e){
            e.printStackTrace();
        }
        return status;
    }
}
